import { defineStore } from 'pinia';
import { authApi } from '@/api/auth.js';
import { jwtDecode } from 'jwt-decode';

export const useAuthStore = defineStore('auth', {
    state: () => ({
        user: null,
        accessToken: null,
        refreshToken: null,
        authorities: [],
        isLoading: false,
        error: null,
        _initialized: false // 初始化状态标记
    }),

    getters: {
        isAuthenticated: (state) => {
            if (!state.accessToken) return false;
            try {
                const decoded = jwtDecode(state.accessToken);
                return decoded.exp * 1000 > Date.now();
            } catch {
                return false;
            }
        },
        isAdmin: (state) => state.user?.userType === 'ADMIN',
        isTeacher: (state) => state.user?.userType === 'TEACHER',
        isStudent: (state) => state.user?.userType === 'STUDENT',
        hasAuthority: (state) => (authority) => state.authorities.includes(authority),
        tokenExpiration: (state) => {
            if (!state.accessToken) return null;
            try {
                const decoded = jwtDecode(state.accessToken);
                return decoded.exp * 1000;
            } catch {
                return null;
            }
        },
        // 安全访问器
        safeUser: (state) => state.user || {},
        safeAccessToken: (state) => state.accessToken || '',
        safeAuthorities: (state) => [...state.authorities]
    },

    actions: {
        // 安全解析localStorage数据
        _safeParseLocalStorage(key, defaultValue) {
            try {
                const item = localStorage.getItem(key);
                return item ? JSON.parse(item) : defaultValue;
            } catch (error) {
                console.error(`解析localStorage数据[${key}]失败:`, error);
                return defaultValue;
            }
        },

        // 持久化认证数据
        persistAuthData() {
            try {
                if (this.accessToken) {
                    localStorage.setItem('accessToken', this.accessToken);
                }
                if (this.refreshToken) {
                    localStorage.setItem('refreshToken', this.refreshToken);
                }
                if (this.user) {
                    localStorage.setItem('user', JSON.stringify(this.user));
                }
                localStorage.setItem('authorities', JSON.stringify(this.authorities));
            } catch (error) {
                console.error('持久化认证数据失败:', error);
            }
        },

        async login(credentials) {
            this.isLoading = true;
            this.error = null;

            try {
                const response = await authApi.login(credentials);
                const { accessToken, refreshToken, userInfo, authorities = [] } = response.data;

                // 验证token有效性
                const decoded = jwtDecode(accessToken);
                if (!decoded.exp || decoded.exp * 1000 <= Date.now()) {
                    throw new Error('令牌已过期');
                }

                this.accessToken = accessToken;
                this.refreshToken = refreshToken;
                this.user = userInfo;
                this.authorities = authorities;

                if (authApi.setAuthHeader) {
                    authApi.setAuthHeader(accessToken);
                }
                this.persistAuthData();

                return response.data;
            } catch (error) {
                this.clearAuthData();
                this.error = error.response?.data?.message || error.message;
                throw error;
            } finally {
                this.isLoading = false;
            }
        },

        async fetchUser() {
            if (!this.isAuthenticated) {
                throw new Error('用户未认证');
            }

            this.isLoading = true;
            try {
                const response = await authApi.getCurrentUser();
                this.user = response.data;
                this.persistAuthData();
                return this.user;
            } catch (error) {
                if (error.response?.status === 401) {
                    try {
                        await this.refreshAccessToken();
                        return await this.fetchUser();
                    } catch (refreshError) {
                        await this.logout();
                        throw refreshError;
                    }
                }
                throw error;
            } finally {
                this.isLoading = false;
            }
        },

        clearAuthData() {
            try {
                localStorage.removeItem('accessToken');
                localStorage.removeItem('refreshToken');
                localStorage.removeItem('user');
                localStorage.removeItem('authorities');
                if (authApi.setAuthHeader) {
                    authApi.setAuthHeader(null);
                }
            } catch (error) {
                console.error('清除认证数据失败:', error);
            } finally {
                this.$reset();
            }
        },

        async logout() {
            try {
                // 即使API调用失败也要清除本地状态
                if (this.accessToken && authApi.logout) {
                    await authApi.logout().catch(error => {
                        console.error('退出API调用失败:', error);
                    });
                }
            } finally {
                this.clearAuthData();
            }
        },

        async refreshAccessToken() {
            if (!this.refreshToken) {
                throw new Error('没有可用的刷新令牌');
            }

            try {
                const response = await authApi.refreshToken(this.refreshToken);
                const { accessToken, refreshToken } = response.data;

                const decoded = jwtDecode(accessToken);
                if (!decoded.exp || decoded.exp * 1000 <= Date.now()) {
                    throw new Error('新令牌已过期');
                }

                this.accessToken = accessToken;
                this.refreshToken = refreshToken || this.refreshToken;

                if (authApi.setAuthHeader) {
                    authApi.setAuthHeader(accessToken);
                }
                this.persistAuthData();

                return response.data;
            } catch (error) {
                console.error('刷新令牌失败:', error);
                await this.logout();
                throw error;
            }
        },


        async initialize() {
            if (this._initialized) return;

            const accessToken = localStorage.getItem('accessToken');
            if (!accessToken) {
                this._initialized = true;
                return;
            }

            this.isLoading = true;
            try {
                const decoded = jwtDecode(accessToken);
                const isExpired = decoded.exp * 1000 < Date.now();

                this.accessToken = accessToken;
                this.refreshToken = localStorage.getItem('refreshToken');
                this.user = this._safeParseLocalStorage('user', null);
                this.authorities = this._safeParseLocalStorage('authorities', []);

                if (isExpired && this.refreshToken) {
                    await this.refreshAccessToken();
                } else {
                    // 延迟加载authApi以避免循环依赖
                    const { authApi } = await import('@/api/auth');
                    authApi.setAuthHeader(accessToken);
                }

                // 如果用户信息不完整，尝试获取
                if (!this.user?.id) {
                    await this.fetchUser().catch(error => {
                        console.warn('获取用户信息失败:', error);
                        this.clearAuthData();
                    });
                }
            } catch (error) {
                console.error('初始化认证失败:', error);
                this.clearAuthData();
            } finally {
                this._initialized = true;
                this.isLoading = false;
            }
        },

        // 安全检查方法
        checkAuth() {
            if (!this.isAuthenticated) {
                throw new Error('用户未认证');
            }
            return true;
        },

        // 角色验证方法
        requireRole(role) {
            if (!this.user || this.user.userType !== role) {
                throw new Error(`需要${role}权限`);
            }
            return true;
        },

        // 权限验证方法
        requireAuthority(authority) {
            if (!this.hasAuthority(authority)) {
                throw new Error(`需要${authority}权限`);
            }
            return true;
        }
    }
});